//
//  UITextField_Extension.swift
//  swiftProductTemplate
//
//  Created by 刘圣洁 on 2025/6/19.
//

import UIKit

extension UITextField {
    // MARK: - 快捷创建方法
    static func make(
        placeholder: String? = nil,
        font: UIFont = AppTheme.Fonts.body,
        textColor: UIColor = AppTheme.Colors.textPrimary,
        placeholderColor: UIColor = AppTheme.Colors.textSecondary,
        keyboardType: UIKeyboardType = .default,
        isSecureTextEntry: Bool = false,
        toView: UIView
    ) -> UITextField {
        let textField = UITextField()
        textField.placeholder = placeholder
        textField.font = font
        textField.textColor = textColor
        textField.attributedPlaceholder = NSAttributedString(
            string: placeholder ?? "",
            attributes: [.foregroundColor: placeholderColor]
        )
        textField.keyboardType = keyboardType
        textField.isSecureTextEntry = isSecureTextEntry
        toView.addSubview(textField)
        return textField
    }
    
    // MARK: - 链式配置方法
    @discardableResult
    func withPlaceholder(_ placeholder: String?, color: UIColor = .secondaryLabel) -> Self {
        self.placeholder = placeholder
        self.attributedPlaceholder = NSAttributedString(
            string: placeholder ?? "",
            attributes: [.foregroundColor: color]
        )
        return self
    }
    
    @discardableResult
    func withFont(_ font: UIFont) -> Self {
        self.font = font
        return self
    }
    
    @discardableResult
    func withTextColor(_ color: UIColor) -> Self {
        self.textColor = color
        return self
    }
    
    @discardableResult
    func withKeyboardType(_ keyboardType: UIKeyboardType) -> Self {
        self.keyboardType = keyboardType
        return self
    }
    
    @discardableResult
    func withReturnKeyType(_ returnKeyType: UIReturnKeyType) -> Self {
        self.returnKeyType = returnKeyType
        return self
    }
    
    @discardableResult
    func withIsSecureTextEntry(_ isSecure: Bool) -> Self {
        self.isSecureTextEntry = isSecure
        return self
    }
    
    @discardableResult
    func withTextAlignment(_ alignment: NSTextAlignment) -> Self {
        self.textAlignment = alignment
        return self
    }
    
    @discardableResult
    func withClearButtonMode(_ mode: UITextField.ViewMode) -> Self {
        self.clearButtonMode = mode
        return self
    }
    
    @discardableResult
    func withBorderStyle(_ style: UITextField.BorderStyle) -> Self {
        self.borderStyle = style
        return self
    }
    
    @discardableResult
    func withCornerRadius(_ radius: CGFloat) -> Self {
        layer.cornerRadius = radius
        layer.masksToBounds = true
        return self
    }
    
    @discardableResult
    func withBackgroundColor(_ color: UIColor?) -> Self {
        self.backgroundColor = color
        return self
    }
    
    @discardableResult
    func withBorder(width: CGFloat, color: UIColor) -> Self {
        layer.borderWidth = width
        layer.borderColor = color.cgColor
        return self
    }
    
    @discardableResult
    func withShadow(
        color: UIColor = .black,
        radius: CGFloat = 3,
        offset: CGSize = CGSize(width: 0, height: 2),
        opacity: Float = 0.1
    ) -> Self {
        layer.shadowColor = color.cgColor
        layer.shadowRadius = radius
        layer.shadowOffset = offset
        layer.shadowOpacity = opacity
        layer.masksToBounds = false
        return self
    }
    
    private struct AssociatedKeys {
        static var maxLength = "maxLength"
    }
    
    // MARK: - 输入限制
    @discardableResult
    func limitMaxLength(_ maxLength: Int) -> Self {
        addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
        objc_setAssociatedObject(self, &AssociatedKeys.maxLength, maxLength, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        return self
    }
    
    @discardableResult
    func limitToDigits() -> Self {
        addTarget(self, action: #selector(validateDigitsOnly), for: .editingChanged)
        return self
    }
    
    @discardableResult
    func limitToLetters() -> Self {
        addTarget(self, action: #selector(validateLettersOnly), for: .editingChanged)
        return self
    }
    
    @objc private func textFieldDidChange(_ textField: UITextField) {
        guard let maxLength = objc_getAssociatedObject(self, &AssociatedKeys.maxLength) as? Int,
              let text = textField.text, text.count > maxLength else { return }
        
        textField.text = String(text.prefix(maxLength))
    }
    
    @objc private func validateDigitsOnly() {
        guard let text = text else { return }
        let allowedCharacters = CharacterSet.decimalDigits
        let characterSet = CharacterSet(charactersIn: text)
        
        if !allowedCharacters.isSuperset(of: characterSet) {
            self.text = text.components(separatedBy: allowedCharacters.inverted).joined()
        }
    }
    
    @objc private func validateLettersOnly() {
        guard let text = text else { return }
        let allowedCharacters = CharacterSet.letters.union(.whitespaces)
        let characterSet = CharacterSet(charactersIn: text)
        
        if !allowedCharacters.isSuperset(of: characterSet) {
            self.text = text.components(separatedBy: allowedCharacters.inverted).joined()
        }
    }
}
